package no.saiboten.milkywave.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import no.saiboten.milkywave.entity.Event;
import no.saiboten.milkywave.entity.User;
import no.saiboten.milkywave.service.EventService;

import org.springframework.stereotype.Component;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@Component
public class EventServiceImpl implements EventService {

	Objectify ofy;

	public EventServiceImpl() {
		ObjectifyService.register(Event.class);
		ofy = ObjectifyService.begin();
	}

	@Override
	public Long createEvent() {
		Calendar cal = Calendar.getInstance();

		Event event = new Event();
		event.generateKeyMap();
		event.setDate(cal.getTime());

		ofy.put(event);
		return event.getId();
	}

	@Override
	public void joinEvent(Long eventid, String key) {
		Event event = ofy.get(Event.class, eventid);
		List<String> keyToUserMap = event.getKeyToUserMap();

		String userStr = null;

		for (String string : keyToUserMap) {
			String[] mapInPieces = string.split("=");
			if (mapInPieces[0].equals(key)) {
				userStr = mapInPieces[1];
			}
		}

		if (userStr != null) {
			User user = ofy.get(User.class, userStr);
			event.getUsers().add(user);
			ofy.put(event);
		}
	}

	@Override
	public Event getEvent(Long id) {
		return ofy.get(Event.class, id);
	}

	@Override
	public List<Event> getAllEvents() {
		return ofy.query(Event.class).list();
	}

	@Override
	public List<Event> getEventsInThePast() {
		List<Event> events = ofy.query(Event.class).list();

		List<Event> eventsInThePast = new ArrayList<Event>();
		for (Event event : events) {
			Calendar now = Calendar.getInstance();
			Calendar eventDate = Calendar.getInstance();
			eventDate.setTime(event.getDate());

			if (eventDate.get(Calendar.YEAR) == now.get(Calendar.YEAR)
					&& eventDate.get(Calendar.MONTH) == now.get(Calendar.MONTH)
					&& eventDate.get(Calendar.DAY_OF_MONTH) == now
							.get(Calendar.DAY_OF_MONTH)) {
				// Do nothing
			} else {
				eventsInThePast.add(event);
			}
		}
		Collections.sort(eventsInThePast);
		return eventsInThePast;
	}

	@Override
	public Event getCurrentEvent() {
		List<Event> events = ofy.query(Event.class).list();
		Calendar now = Calendar.getInstance();

		for (Event event : events) {
			Calendar eventDate = Calendar.getInstance();
			eventDate.setTime(event.getDate());

			if (eventDate.get(Calendar.YEAR) == now.get(Calendar.YEAR)
					&& eventDate.get(Calendar.MONTH) == now.get(Calendar.MONTH)
					&& eventDate.get(Calendar.DAY_OF_MONTH) == now
							.get(Calendar.DAY_OF_MONTH)) {
				return event;
			}
		}

		return null;
	}
}
